import java.util.PriorityQueue;
import java.util.TimerTask;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2024-07-27
 * Time: 9:38
 */

class MyTimer{
    private static Object locker = new Object();
    private PriorityQueue<MyTimerTask> priorityQueue = new PriorityQueue<>();

    public MyTimer() {
        Thread t = new Thread(() -> {
            synchronized(locker) {
                while(true) {
                        while (priorityQueue.isEmpty()) {
                            try {
                                locker.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        MyTimerTask current = priorityQueue.peek();
                        if(current.getTime() <= System.currentTimeMillis()) {
                            current.run();
                            priorityQueue.poll();
                        }else {
                            try {
                                locker.wait(current.getTime() - System.currentTimeMillis());
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
        });
        t.start();
    }

    public void schedule(Runnable runnable,long delay) {
        synchronized(locker) {
            MyTimerTask myTimerTask = new MyTimerTask(runnable,delay);
            priorityQueue.offer(myTimerTask);
            locker.notify();
        }
    }

}

class MyTimerTask implements Comparable<MyTimerTask>{
    private long time;

    private Runnable runnable;

    public MyTimerTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public long getTime() {
        return this.time;
    }

    public void run() {
        runnable.run();
    }


    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time-o.time);
    }
}




public class Demo2 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(()->{
            System.out.println("hello 3000");
        },3000);

        myTimer.schedule(()->{
            System.out.println("hello 2000");
        },2000);

        myTimer.schedule(()->{
            System.out.println("hello 1000");
        },1000);

        System.out.println("线程开始");
    }
}
